import { createRouter, createWebHistory } from "vue-router";
import { menuList } from "./menuList";
import { ElLoading } from "element-plus";

let loading = null; //页面加载

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/404",
      name: "404",
      // redirect: '/404'
      component: () => import("@/layout/404.vue"),
    },
    {
      path: "/:pathMatch(.*)",
      redirect: "/404",
    },
    {
      path: "/",
      name: "主页",
      component: () => import("@/views/Home.vue"),
    },
    {
      path: "/large-screen/bulletin-board",
      name: "看板",
      component: () => import("@/views/large-screen/bulletinBoard.vue"),
    },
    // {
    //   path: "/3d/demo1",
    //   name: "3D案例1",
    //   component: () => import("@/views/3D/demo1.vue"),
    // },
    {
      path: "/css-layout/waterfall-flow",
      name: "div瀑布流",
      component: () => import("@/views/css-layout/waterfall-flow.vue"),
    },
    {
      path: "/management",
      name: "后台管理",
      component: () => import("@/views/manager/index.vue"),
    },
  ],
});

// 在路由完成初始导航时调用，如果有异步操作放置到这里
router.isReady().then(() => {
  // 重新进入当前路由页面
  router.push(router.currentRoute.value);
});

router.beforeEach(async (to, from, next) => {
  loading = ElLoading.service({
    lock: true,
    text: "进入系统中...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  await generateRoutes();

  next();
  loading && loading.close();

  // const token = localStorage.getItem("token");
  // // 检查to.path是否存在于免登陆白名单
  // if (inWhiteList(to.path)) {
  //   if (to.path === "/login" && token) {
  //     // 避免重复登录
  //     next({ path: "/" });
  //   } else {
  //     next();
  //   }
  //   return false;
  // }
  // // 判断是否已经登录，未登录则重定向到登录页（通过query传参记录原来的路径）
  // if (!token) {
  //   const toPath = to.fullPath !== "/login" ? to.fullPath : "/";
  //   next({
  //     path: "/login",
  //     query: { redirect: toPath },
  //   });
  // } else {
  //   next();
  // }
});

// 重置路由
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

export function generateRoutes() {
  return new Promise((resolve, reject) => {
    // 获取菜单列表
    const _asyncRoutes = menuList;
    const routes = _asyncRoutes.map((item) => {
      const route = { ...item };
      return route;
    });
    const asyncRoutes = routes; //toTree(routes)
    asyncRoutes.forEach((route) => {
      router.addRoute(route);
    });
    resolve();
  });
}

export default router;
